import React, {useState,useEffect} from 'react'
import Pagecomponent from './pageComponent/Pagecomponent';
import './Posts.css'
import {changeTime} from './tool';

var pageNum;
const Posts = () => {
    const [dataList, setDataList] = useState([]);
    const [totalPage, setTotalPage] = useState(15);
    const [posts,setPosts] = useState([]);
    const [sortPosts,setSort] = useState([]);
    const [val,setValue] = useState('');
    const [dis,setDis] = useState(['block','none']);

    useEffect(()=>{
        fetch(`https://api.124ss.xyz:2355/endsquare?rand=$11`,{
          method: "GET",
          mode: "cors",
          headers: {
            "Content-Type": "text/plain"
          }
    
        }).then(res => {
          return res.json();
        })
        .then(res =>{
            var arr = [];
            var postsObj = [];
            res.forEach((item,index) => {
              postsObj = [
                item['posts_text'],
                item['posts_image'],
                item['posts_time'],
                item['open_id'],
                item['posts_id']
              ]
              arr.push(postsObj);
            });
            setPosts(arr);
        })
        .catch((err)=>{
          console.log("err:",err);
        })
      },[])

      const getCurrentPage = (currentPage) => {
        setDataList(posts[currentPage-1])
        pageNum = currentPage;
      }

      const DelItem = (idx,item) => {
        fetch(`https://api.124ss.xyz:2355/enddelPosts/${item[4]}`,{
          method: "delete",
          mode: "cors",
          headers: {
            "Content-Type": "text/plain"
          },
          body: JSON.stringify({
            posts_id: item[4]
          })
    
        }).then(res => {
          return res.text();
        })
        .then(res =>{
          console.log(res)
        } )
        .catch((err)=>{
          console.log("err:",err);
        })
        
        let newPosts = posts.filter((_,index)=>idx!=index);
        setPosts(newPosts);
    
      }

      const SearchPost = () => {
        var sortObj = [];
        var sortArr = [];
        for(var i = 0; i < posts.length; i++){
          if(posts[i][3] == val){
            sortObj = [
              posts[i][0],
              posts[i][2]
            ];

            sortArr.push(sortObj);

            setDis(['none','block']);
          }
        }
        setSort(sortArr);
      }

      const BackPost = () => {
        setDis(['block','none']);
      }

    return (
        <div id='posts-container'>
          <div>
            <input style={{width:'200px',height:'30px'}} 
                    value = {val} 
                    onChange = {e => {setValue(e.target.value)}} 
                    type='search' 
                    placeholder='Please Enter the Openid' 
            />
            <button id='sort-btn' onClick={() => SearchPost()}>搜索</button>
            <button id='sort-btn' onClick={() => BackPost()}>返回</button>
          </div>
          <div id='posts-table' style={{display: dis[0]}}>
            <table id='posts-tab'>
              <thead>
                <tr>
                  <th>序号</th>
                  <th style={{width:300}}>帖子内容</th>
                  <th>发帖时间</th>
                  <th>OPENID</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {
                  posts.slice(4*(pageNum-1),4*pageNum).map((item, index) =>
                    <tr key={index}>
                      <td>
                        {(pageNum-1)*4+index+1}
                      </td>
                      <td>
                        {item[0]}
                      </td>
                      <td>{changeTime(Number(item[2]))}</td>
                      <td>{item[3]}</td>
                      <td>
                        <button id='posts-btn' onClick={() => DelItem(index,item)}>
                          删除
                        </button>
                      </td>
                    </tr>)
                }
              </tbody>
            </table>
          </div>

          <div id='posts-table' style={{display: dis[1]}}>
            <table id='posts-tab'>
              <thead>
                <tr>
                  <th>序号</th>
                  <th style={{width:300}}>帖子内容</th>
                  <th>发帖时间</th>
                </tr>
              </thead>
              <tbody>
                {
                  sortPosts.slice(4*(pageNum-1),4*pageNum).map((item, index) =>
                    <tr key={index}>
                      <td>
                        {(pageNum-1)*4+index+1}
                      </td>
                      <td>
                        {item[0]}
                      </td>
                      <td>{changeTime(Number(item[1]))}</td>
                    </tr>)
                }
              </tbody>
            </table>
          </div>
          
        <div id='posts-page'>
          <Pagecomponent totalPage={totalPage} pageCallbackFn={getCurrentPage}/>
        </div>
      </div>
    )
}

export default Posts
